package xeroxware.framework.datasource;

import java.lang.reflect.Method;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * <pre>
 * DataSourceAspect
 * </pre>
 * 
 * @since 2013. 3. 7.
 * @author XEROXER
 */
@Aspect
@Component
@Order(value = 1)
public class DataSourceAspect implements InitializingBean {

	@Around("execution(* xeroxware.framework..*Service.*(..))")
	public Object doServiceProfiling(ProceedingJoinPoint joinPoint) throws Throwable {

		final String methodName = joinPoint.getSignature().getName();
		final MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
		Method method = methodSignature.getMethod();

		if (method.getDeclaringClass().isInterface()) {
			method = joinPoint.getTarget().getClass().getDeclaredMethod(methodName, method.getParameterTypes());
		}

		DataSource dataSource = (DataSource) method.getAnnotation(DataSource.class);

		if (dataSource != null) {
			ContextHolder.setDataSourceType(dataSource.value());
		} else {
			ContextHolder.setDataSourceType(DataSourceType.XEROXWARE);
		}

		Object returnValue = joinPoint.proceed();
		ContextHolder.clearDataSourceType();

		return returnValue;
	}

	@Override
	public void afterPropertiesSet() throws Exception {

	}
}
